import request from '@/utils/request'

/**
 * 根据键名获取单个配置项
 * @param {string} key - 配置键名
 * @returns {Promise} - 返回Promise对象
 */
export async function getConfigByKey(key) {
  if (!key) {
    console.error('配置键名不能为空');
    return {
      success: false,
      data: null,
      message: '配置键名不能为空'
    };
  }

  try {
    console.log(`正在获取配置项: ${key}`);
    const response = await request({
      url: `/admin/configs/mp/get/${key}`,
      method: 'get'
    });
    
    console.log('获取配置响应:', response);
    
    // 返回配置项的值
    return {
      success: true,
      data: response.data,
      message: '获取成功'
    };
  } catch (error) {
    console.error(`获取配置项[${key}]失败:`, error);
    // 提取更详细的错误信息
    let errorMessage = error.message || `获取配置项[${key}]失败`;
    if (error.response) {
      const status = error.response.status;
      const data = error.response.data;
      
      if (data && data.message) {
        errorMessage = data.message;
      } else if (status === 401) {
        errorMessage = '未授权，请先登录';
      } else if (status === 404) {
        errorMessage = `配置项[${key}]不存在`;
      }
      
      console.error(`HTTP状态码: ${status}, 错误信息: ${errorMessage}`);
    }
    
    return {
      success: false,
      data: null,
      message: errorMessage
    };
  }
}

/**
 * 获取所有公开配置
 * @returns {Promise} - 返回Promise对象
 */
export async function getPublicConfigs() {
  try {
    const response = await request({
      url: '/admin/configs/public',
      method: 'get'
    })
    
    return {
      success: true,
      data: response.data,
      message: '获取成功'
    }
  } catch (error) {
    console.error('获取公开配置失败:', error)
    return {
      success: false,
      data: {},
      message: error.message || '获取公开配置失败'
    }
  }
}

/**
 * 更新配置项
 * @param {string} key - 配置键名
 * @param {any} value - 配置值
 * @param {object} options - 额外选项，如类型、分组、描述等
 * @returns {Promise}
 */
export async function updateConfig(key, value, options = {}) {
  try {
    const { type, group, description, is_public } = options
    
    const response = await request({
      url: `/admin/configs/${key}`,
      method: 'put',
      data: {
        value,
        type,
        group,
        description,
        is_public
      }
    })
    
    return {
      success: true,
      message: '更新成功'
    }
  } catch (error) {
    console.error(`更新配置项[${key}]失败:`, error)
    return {
      success: false,
      message: error.message || `更新配置项[${key}]失败`
    }
  }
} 